<template>
    <div class="user-selector">
        <el-select v-model="selectedUserId" :placeholder="placeholder" filterable class="user-select"
            @change="handleChange">
            <el-option-group v-for="dept in deptTreeData" :key="dept.id" :label="dept.label">
                <el-option v-for="user in dept.children" :key="user.id" :label="user.label" :value="user.id">
                    <span class="user-option">
                        <el-icon>
                            <User />
                        </el-icon>
                        <span>{{ user.label }}</span>
                    </span>
                </el-option>
            </el-option-group>
        </el-select>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Folder, User } from '@element-plus/icons-vue'
import { getUserDeptTree } from '@/api/department'

// 定义组件Props
const props = defineProps({
    modelValue: {
        type: [Number, null],
        default: null
    },
    placeholder: {
        type: String,
        default: '请选择用户'
    }
})

// 定义事件
const emit = defineEmits(['update:modelValue', 'change'])

interface TreeNode {
    id: string | number;
    label: string;
    isUser: boolean;
    disabled?: boolean;
    children?: TreeNode[];
    originalData?: any;
}

// 部门树数据
const deptTreeData = ref<TreeNode[]>([])

// 已选中的用户ID
const selectedUserId = ref<number | null>(props.modelValue)

// 监听props.modelValue变化
watch(() => props.modelValue, (newValue) => {
    selectedUserId.value = newValue as number
}, { immediate: true })

// 监听选中值变化，触发v-model更新
watch(() => selectedUserId.value, (newValue) => {
    emit('update:modelValue', newValue)
})

// 处理选择变化
const handleChange = (value: number) => {
    emit('change', value);
}

// 获取并转换用户部门树数据
const fetchUserDeptTree = async () => {
    try {
        const apiResponse = await getUserDeptTree(0);

        // 保存完整的API响应数据，使用类型断言避免TypeScript错误
        const data = (apiResponse as any)?.Data || [];
        console.log('API返回数据:', data);

        // 直接转换数据到树节点格式，只展示部门名称和用户名称
        const treeNodes: TreeNode[] = data.map((dept: any) => {
            // 创建部门节点，保留完整原始数据
            const deptNode: TreeNode = {
                id: `dept-${dept?.DeptId || 0}`,
                label: dept?.DepartmentName || '未命名部门',
                isUser: false,
                disabled: true, // 部门节点不可选
                originalData: dept, // 保存完整的原始数据
                children: []
            };

            // 处理部门下的用户
            if (dept?.Children) {
                dept.Children.forEach((role: any) => {
                    if (role?.Users) {
                        role.Users.forEach((user: any) => {
                            if (!user) return;

                            // 创建用户节点，保留完整原始数据
                            const userNode: TreeNode = {
                                id: user.UserId || 0,
                                label: user.RealName || user.UserName || '未命名用户',
                                isUser: true,
                                disabled: false, // 用户节点可选
                                originalData: user // 保存完整的原始数据
                            };

                            // 添加用户节点到部门的children
                            deptNode.children!.push(userNode);
                        });
                    }
                });
            }

            // 只返回有用户的部门
            return deptNode.children && deptNode.children.length > 0 ? deptNode : null;
        }).filter(Boolean) as TreeNode[]; // 过滤掉没有用户的部门

        // 赋值结果
        deptTreeData.value = treeNodes;
        console.log('部门树数据加载完成', treeNodes.length);
    } catch (error) {
        console.error('获取用户部门树失败:', error);
        deptTreeData.value = [];
    }
};

// 组件挂载时获取数据
onMounted(() => {
    fetchUserDeptTree()
})
</script>

<style scoped>
.user-selector {
    width: 100%;
}

.user-select {
    width: 100%;
}

.user-option {
    display: flex;
    align-items: center;
    font-size: 14px;
}

.user-option .el-icon {
    margin-right: 6px;
    color: #909399;
}
</style>